package com.pds.web.controller.common;

import com.pds.common.constant.Constants;
import com.pds.common.core.domain.R;
import com.pds.common.utils.minio.MinioUtils;
import com.pds.system.domain.FileUpload;
import com.pds.system.service.IFileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private IFileUploadService fileUploadService;

    @PostMapping("/upload")
    public R minioUpload(@RequestParam(value = "file") MultipartFile file){
        String fileName = file.getOriginalFilename();
        String objectName = "file/" + fileName;
        String url = null;
        try {
            url = minioUtils.putObject(file, objectName, "enviroment");
            if(!Objects.isNull(url)){
                int index = url.indexOf("//");
                String pathUrl = url.substring(index+2);
                index = pathUrl.indexOf("/");
                String tempUrl = pathUrl.substring(index);
                index = tempUrl.indexOf("?");
                url = tempUrl.substring(0,index);

            }
        } catch (Exception e) {
            log.error("上传失败",e);
        }
        return R.ok(url);
    }

    @DeleteMapping
    public R delete(String objectName){
        try {
            minioUtils.removeObject("enviroment",objectName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 文件上传，并返回文件id、名称信息
     * 支持单个、批量上传
     * @param files
     * @param filesType 默认永久保存，1可以过期
     * @return
     */
    @PostMapping("/batchUpload")
    public R uploadAndReturnFileID(@RequestParam(value = "files") MultipartFile[] files,
                                   @RequestParam(value = "filesType",required = false) String filesType) throws Exception {
        log.info("批量上传文件开始");
        //上传文件格式校验
        if(null != files && !files[0].isEmpty()){
            String type = "";
            for(MultipartFile file : files){
                String fileName = file.getOriginalFilename();
                String  fileType = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
                if(!Constants.ALLOWED_FORMAT.contains(fileType)){
                    if(StringUtils.isEmpty(type)){
                        type = fileType;
                    }else{
                        type = type +"," + fileType;
                    }
                }
            }
            if(StringUtils.isNotEmpty(type)){
                return R.fail("文件格式"+type+"不允许上传!");
            }
        }
        if(null != files && !files[0].isEmpty()) {
            List<FileUpload> list = new ArrayList<>(files.length);
            for (MultipartFile file : files) {
                FileUpload fileUpload =  fileUploadService.uploadAndReturnFileID(file,filesType);
                list.add(fileUpload);
            }
            return R.ok(list,"文件上传成功");
        }else{
            return R.fail("没有需要上传的文件！") ;
        }
    }

    /**
     * 通过文件id下载文件
     * @param attachmentId 文件id
     * @param httpServletResponse
     */
    @RequestMapping("/downloadByFileId")
    public void downloadByfileid(String attachmentId, HttpServletResponse httpServletResponse) {
        if(StringUtils.isEmpty(attachmentId)){
            log.error("必输项参数为空!");
        }
        //根据文件ID查询文件信息
        FileUpload fileUpload= fileUploadService.selectFileUploadById(attachmentId);
        InputStream inputStream = null;
        try {
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUpload.getFileName(), "UTF-8"));
            httpServletResponse.setContentType(minioUtils.getContentType(fileUpload.getFileName()));
            httpServletResponse.setCharacterEncoding("UTF-8");
            inputStream = fileUploadService.downLoadInfoByName(fileUpload.getBucketname(),fileUpload.getFileSaveName());
            IOUtils.copy(inputStream, httpServletResponse.getOutputStream());
        } catch (Exception e) {
            log.error("附件下载失败,  bucketName: {}, objectName: {}", fileUpload.getBucketname(), fileUpload.getFileSaveName(),e);
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.error("流关闭异常",e);
                }
            }

        }
    }

}
